package controller

import (
	"strconv"
	"strings"
	"system-admin/internal/app/web/service/auth"
	"system-admin/internal/app/web/service/role"

	"192.168.1.75/go-pkg/response"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
)

type Role struct {
}

// All 所有角色
func (Role) All(c *gin.Context) {
	value, total := role.RoleList(c.GetString("user_id"), 0, 0)
	response.JSON(c, gin.H{
		"list":  value,
		"total": total,
	}, nil)
}

// List 角色列表
func (Role) List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	limit, _ := strconv.Atoi(c.Query("limit"))
	value, total := role.RoleList(c.GetString("user_id"), page, limit)
	response.JSON(c, gin.H{
		"list":  value,
		"total": total,
	}, nil)
}

// Add 新增角色
func (Role) Add(c *gin.Context) {
	var params struct {
		Name string `json:"name"`
	}
	c.ShouldBindWith(&params, binding.JSON)
	roleID, err := role.AddRole(c.GetString("user_id"), params.Name)
	if err != nil {
		response.JSON(c, gin.H{
			"role_id": "",
		}, err)
	} else {
		response.JSON(c, gin.H{
			"role_id": roleID,
		}, nil)
	}
}

// Edit 编辑角色
func (Role) Edit(c *gin.Context) {
	var params struct {
		RoleID string `json:"role_id"`
		Name   string `json:"name"`
	}
	c.ShouldBindWith(&params, binding.JSON)
	err := role.EditRole(c.GetString("user_id"), params.RoleID, params.Name)
	response.JSON(c, nil, err)
}

// Delete 删除角色
func (Role) Delete(c *gin.Context) {
	var params struct {
		RoleID string `json:"role_id"`
	}
	c.ShouldBindWith(&params, binding.JSON)
	err := role.DeleteRole(c.GetString("user_id"), params.RoleID)
	response.JSON(c, nil, err)
}

// GetAuthRules 获取当前登录用户的权限规则
func (Role) GetAuthRules(c *gin.Context) {
	rules, err := auth.GetRoleAuthRules(c.GetString("role_id"))
	if err != nil {
		response.JSON(c, []string{}, err)
	} else {
		response.JSON(c, rules, err)
	}
}

// GetRoleAuthRules 获取指定角色的权限规则
func (Role) GetRoleAuthRules(c *gin.Context) {
	rules, err := auth.GetRoleAuthRules(c.Query("role_id"))
	if err != nil {
		response.JSON(c, []string{}, err)
	} else {
		response.JSON(c, rules, err)
	}
}

// GetRoleAuthRules 获取指定角色的权限规则
func (Role) GetRoleAuthRulesChecked(c *gin.Context) {
	rules, err := auth.GetRoleAuthRulesWithChecked(c.GetString("user_id"), c.Query("role_id"))
	if err != nil {
		response.JSON(c, []string{}, err)
	} else {
		response.JSON(c, rules, err)
	}
}

// SetRoleAuthRules 设置指定角色的权限规则
func (Role) SetRoleAuthRules(c *gin.Context) {
	var params struct {
		RoleID  string `json:"role_id"`
		RuleIDs string `json:"rule_ids"`
	}
	c.ShouldBindBodyWith(&params, binding.JSON)
	ruleIDArray := strings.Split(strings.TrimSpace(params.RuleIDs), ",")
	err := auth.SetRoleAuthRules(c.GetString("user_id"), c.GetString("role_id"), params.RoleID, ruleIDArray)
	response.JSON(c, nil, err)
}
